<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\BaseController;
use app\common\controller\Frontend;
use app\common\model\Contact as ContactModel;
use think\Request;


class Contact extends Frontend
{
    //留言页面
    public function index(Request $request)
    {
        return view('contact/index');
    }

    //留言保存
    public function save(Request $request)
    {
        try {
            $data = $request->post();
            if (!empty($user = session('user'))) {
                $data['user_id'] = $user['id'];
            }
            ContactModel::create($data);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('提交成功','/contact/list');
    }

    //留言列表
    public function list(Request $request)
    {
        $page = $request->get("page", 1) ?: 1;
        $contactList = ContactModel::where('user_id', session('user.id'))->select()->toArray();

        //分页
        $total = count($contactList);
        $totalPage = ceil(count($contactList) / 6);
        $contactList = array_slice($contactList, ($page - 1) * 6, 6);
        return view('contact/list', [
            'contactList' => $contactList,
            'total' => $total,
            'totalPage' => $totalPage,
            'page' => $page
        ]);
    }
}
